<template>
    <div class="white-box">
        <div class="table-mb">
            <el-button
                type="primary"
                @click="onClickAdd"
                v-hasPermi="['enttp:config:add']"
                >添加地址</el-button
            >
        </div>

        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">地址类型：</span>
                <el-select
                    v-model="state.addrType"
                    placeholder="请选择地址类型"
                    clearable
                >
                    <el-option label="寄件地址" :value="1" />
                    <el-option label="收货地址" :value="2" />
                </el-select>
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <div class="table-mb" v-hasPermi="['enttp:config:del']">
            <el-button @click="onClickDel()">批量删除地址</el-button>
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @selection-change="selectionChange"
            @sort-change="sortChange"
        >
            <el-table-column
                v-hasPermi="['enttp:config:del']"
                type="selection"
                width="55"
            />
            <el-table-column
                prop="memberName"
                label="联系人"
                min-width="150"
                fixed="left"
            ></el-table-column>
            <el-table-column
                prop="memberPhone"
                label="电话"
                min-width="160"
                sortable="custom"
            ></el-table-column>
            <el-table-column label="省市区" min-width="200">
                <template #default="{ row }">
                    {{ row.province + row.city + row.district }}
                </template>
            </el-table-column>
            <el-table-column prop="address" label="详细地址" min-width="200">
            </el-table-column>
            <el-table-column label="类型" min-width="100" sortable="custom">
                <template #default="{ row }">
                    {{ ["寄件地址", "收货地址"][row.addrType - 1] }}
                </template>
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                min-width="100"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{ dictStore.getDictMemberName("data_status", row.status) }}
                </template>
            </el-table-column>
            <el-table-column
                prop="created"
                label="创建时间"
                min-width="160"
                sortable="custom"
            ></el-table-column>
            <el-table-column
                label="操作"
                width="200"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }">
                    <MoreBtn
                        :buttons="[
                            {
                                props: {
                                    onClick: () => onClickEdit(row.sid),
                                },
                                text: '修改',
                            },
                            {
                                props: {
                                    onClick: () => onClickDel(row.sid),
                                },
                                text: '删除',
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNums >= 100 * pageSize
                        ? `${100 * pageSize}+`
                        : totalNums
                }}&nbsp;条</span
            >
        </el-pagination>
    </div>

    <el-dialog
        v-model="state.show"
        width="550"
        :title="dialogTitle"
        :before-close="handleClose"
    >
        <el-form
            ref="ruleRef"
            :model="state.ruleForm"
            :rules="state.rules"
            label-width="120px"
            class="mt-20"
        >
            <el-form-item label="姓名" prop="memberName">
                <el-input
                    v-model.trim="state.ruleForm.memberName"
                    clearable
                    placeholder="请输入姓名"
                />
            </el-form-item>
            <el-form-item label="电话" prop="memberPhone">
                <el-input
                    v-model.trim="state.ruleForm.memberPhone"
                    clearable
                    placeholder="请输入电话"
                />
            </el-form-item>
            <el-form-item label="省市区" prop="districtCode">
                <el-cascader
                    ref="cascaderRef"
                    v-model="state.ruleForm.districtCode"
                    class="mr-10"
                    :props="regionCodeProps"
                    clearable
                    placeholder="请选择省市区"
                />
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
                <el-input
                    v-model.trim="state.ruleForm.address"
                    clearable
                    placeholder="请输入详细地址"
                />
            </el-form-item>
            <el-form-item label="类型" prop="addrType">
                <el-radio-group v-model="state.ruleForm.addrType">
                    <el-radio :value="1">寄件地址</el-radio>
                    <el-radio :value="2">收货地址</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="state.ruleForm.status">
                    <el-radio :value="0">正常</el-radio>
                    <el-radio :value="1">停用</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item>
                <el-button @click="cancel"> 取消 </el-button>
                <el-button
                    type="primary"
                    :loading="form_loading"
                    @click="submitForm(ruleRef)"
                >
                    {{ isEdit ? "修改" : "添加" }}
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { reactive, onMounted, onActivated, inject, ref, computed } from "vue";
import { useRouter } from "vue-router";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { ElMessageBox } from "element-plus";
import {
    getAddresses,
    delAddresses,
    setDefaultAddress,
    getAddressDetail,
    addAddress,
    editAddress,
} from "@/apis/option/address";
import { getAreas } from "@/apis/common.js";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status");

const router = useRouter();
const $message = inject("$message");
const isEdit = ref(false);
const form_loading = ref(false);
const ruleRef = ref(null);
const cascaderRef = ref(null);
const state = reactive({
    ascended: false,
    sortFieldName: null,
    addrType: null,
    sidList: [],
    show: false,
    ruleForm: {
        addrType: 1,
        address: null,
        city: null,
        defaultAddr: 1,
        district: null,
        districtCode: null,
        latitude: null,
        longitude: null,
        memberName: null,
        memberPhone: null,
        province: null,
        status: 0,
    },
    rules: {
        memberName: [
            { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        memberPhone: [
            { required: true, message: "请输入电话", trigger: "blur" },
        ],
        districtCode: [
            { required: true, message: "请选择省市区", trigger: "blur" },
        ],
        address: [
            { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
    },
    addressList: [],
});
const dialogTitle = computed(() => (isEdit.value ? "修改地址" : "新增地址"));

const regionCodeProps = {
    emitPath: false,
    lazy: true,
    value: "code",
    label: "name",
    lazyLoad(node, resolve) {
        const { value } = node;
        getAreaList(value).then(() => {
            resolve(state.addressList);
        });
    },
};

onActivated(() => {
    pubParams(getList);
});

const getAreaList = async (parentCode = 0) => {
    const res = await getAreas({ parentCode });
    if (res.data.code == 200) {
        res.data.data.forEach((item) => {
            if (item.level === "district") {
                item.leaf = true;
            }
        });
        state.addressList = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    pubParams,
    page,
    pageSize,
    getdata,
    pageSizeNum,
    totalNums,
    openPaging,
} = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getAddresses({
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            sortFieldName: state.sortFieldName,
            addrType: state.addrType,
        })
    );
}

/**
 * 搜索
 * @param {Function} handleSearch 搜索
 */

const handleSearch = () => {
    pubRefreshParams(getList);
};

const onClickAdd = () => {
    state.show = true;
    isEdit.value = false;
};

/**
 * 排序
 * @param {Function} sortChange 排序
 */
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

const onClickEdit = (sid) => {
    state.show = true;
    isEdit.value = true;
    getDetail(sid);
};

/**
 * 点击删除按钮
 * @param {Function} onClickDel 删除地址
 */
const selectionChange = (e) => {
    state.sidList = e.map((item) => item.sid);
};
const onClickDel = async (sid) => {
    if (sid) {
        state.sidList = [sid];
    }
    if (!state.sidList.length) {
        return $message({ message: "请先勾选要删除的数据", type: "warning" });
    }
    await ElMessageBox.confirm("确定删除地址吗？");
    const res = await delAddresses({ sidList: state.sidList });
    if (res.data.code == 200) {
        $message({ message: "删除成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const handleClose = (done) => {
    ruleRef.value.resetFields();
    done();
};

const getDetail = async (sid) => {
    const res = await getAddressDetail({ sid: sid });
    if (res.data.code == 200) {
        state.ruleForm = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const cancel = () => {
    ruleRef.value.resetFields();
    state.show = false;
};

// 提交表单
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            form_loading.value = true;
            let res = null;
            const { data, pathLabels } = cascaderRef.value.getCheckedNodes()[0];
            // 经纬度
            state.ruleForm.latitude = data.latitude;
            state.ruleForm.longitude = data.longitude;
            // 省市区名称
            pathLabels.forEach((item, index) => {
                const key = ["province", "city", "district"][index];
                state.ruleForm[key] = item;
            });
            if (isEdit.value) {
                res = await editAddress(state.ruleForm);
            } else {
                res = await addAddress(state.ruleForm);
            }
            form_loading.value = false;
            if (res.data.code == 200) {
                $message({
                    message: isEdit.value ? "修改成功" : "添加成功",
                    type: "success",
                });
            } else {
                $message({ message: res.data.msg, type: "error" });
            }
        }
    });
};
</script>

<style lang="less" scoped></style>
